const dbClient = require('../utils/db')
const { ObjectID } = require('mongodb')

// 用户列表
exports.getUserList = async (req, res, next) => {
  try {
    let { offset = 1, limit = 10 } = req.query
    offset = Number.parseInt(offset)
    limit = Number.parseInt(limit)
    await dbClient.connect()
    const collection = dbClient.db('test').collection('users')
    const ret = await collection
      .find() // 查询数据
      .skip((offset - 1) * limit) // 跳过多少条 10 1 0 2 10 3 20 n
      .limit(limit) // 拿多少条
    const users = await ret.toArray()
    const usersCount = await collection.countDocuments()
    res.status(200).json({
      users,
      usersCount
    })
  } catch (err) {
    next(err)
  }
}

// 用户注册
exports.register = async (req, res, next) => {
  try {
    // 1. 获取客户端表单数据
    // console.log('req.body', req.body)
    const { user } = req.body

    // 2. 数据验证
    if (!user || !user.username || !user.email || !user.password) {
      return res.status(422).json({
        error: '请求参数不符合规则要求'
      })
    }

    // 3. 把验证通过的数据插入数据库中
    //    成功 -> 发送成功响应
    //    失败 -> 发送失败响应
    await dbClient.connect()

    const collection = dbClient.db('test').collection('users')

    user.createdAt = new Date()
    user.updatedAt = new Date()
    const ret = await collection.insertOne(user)

    user._id = ret.insertedId

    res.status(201).json({
      user
    })
  } catch (err) {
    // 由错误处理中间件统一处理
    next(err)
    // res.status(500).json({
    //   error: err.message
    // })
  }
}

// 根据id查询用户
exports.getUserByID = async (req, res, next) => {
  try {
    await dbClient.connect()
    const collection = dbClient.db('test').collection('users')

    const user = await collection.findOne({
      _id: ObjectID(req.params.id)
    })

    res.status(200).json({
      user
    })
  } catch (err) {
    next(err)
  }
}

// 根据id修改用户
exports.updateUserByID = async (req, res, next) => {
  try {
    await dbClient.connect()
    const collection = dbClient.db('test').collection('users')

    await collection.updateOne(
      {
        _id: ObjectID(req.params.id)
      },
      {
        $set: req.body.user
      }
    )

    const user = await await collection.findOne({
      _id: ObjectID(req.params.id)
    })

    res.status(201).json({
      user
    })
  } catch (err) {
    next(err)
  }
}

// 删除用户
exports.deleteUserByID = async (req, res, next) => {
  try {
    await dbClient.connect()
    const collection = dbClient.db('test').collection('users')
    let result = await collection.deleteOne({
      _id: ObjectID(req.params.id)
    })
    res.status(201).json({
      deletedCount: result.deletedCount
    })
  } catch (err) {
    next(err)
  }
}
